<template>
  <business-layout title='告警管理' customTitle>
    <div class='table-operator' slot='header'>
      <a-form :form='form' layout='inline' @submit='handleQueryData'>
        <a-form-item label=''>
          <a-input placeholder='请输入点位名称' style='width: 200px;' allowClear v-decorator='["positionName"]'/>
        </a-form-item>
        <a-form-item label=''>
          <a-select placeholder='请选择告警类型' style='width: 200px;' allowClear v-decorator='["alarmType"]'
                    :options='alarmTypeList'></a-select>
        </a-form-item>
        <a-form-item>
          <a-button type='primary' html-type='submit'>
            <a-icon type='search' />
            查询
          </a-button>
          <a-button @click='handleResetData' html-type='reset'>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <s-table
      ref='table'
      size='default'
      rowKey='key'
      :columns='columns'
      :data='loadData'
      showPagination='auto'
    >

      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='genTime' slot-scope='text'>
        <span>{{ text| dayjs }}</span>
      </span>
      <span slot='confirmTime' slot-scope='text'>
        <span>{{ text| dayjs }}</span>
      </span>
      <span slot='description' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>
      <span slot='action' slot-scope='text, record'>
        <a @click='handleEdit(record)'>查看详情</a>
        <template>
          <a-divider type='vertical' />
          <a @click='handleConfirm(record)' :disabled='record.confirmBy'>{{record.confirmBy ? '已确认-' + record.confirmBy : '确认'}}</a>
        </template>
        <template>
          <a-divider type='vertical' />
          <a @click='handleSubmit(record)' :disabled='record.status === "submitted"'>{{ record.status === "submitted" ? "工单已提" : "提交工单"}}</a>
        </template>
      </span>
    </s-table>

    <alarm-detail
      ref='AlarmDetail'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
    />

    <confirm-alarm
      ref='confirmAlarm'
      :visible='confirmAlarmVisable'
      :loading='confirmAlarmLoading'
      @cancel='handleConfirmCancel'
      @ok='handleConfirmConfirm'
    />

    <create-work-order
      ref='CreateWorkOrder'
      :model='{ alarmPlace: alarmPlace }'
      :visible='CreateWorkOrderVisable'
      :loading='CreateWorkOrdermLoading'
      @cancel='handleCreateWorkOrderCancel'
      @ok='handleCreateWorkOrderConfirm'
    />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import ConfirmAlarm from './modules/confirmAlarm.vue'
import { createWorkOrder } from '@/api/workerOrder'
import CreateWorkOrder from './modules/CreateWorkOrder.vue'
import {
  getAlarmType,
  findByPage,
  confirm,
  submit
} from '@/api/alarm'
import AlarmDetail from './modules/AlarmDetail.vue'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '发生时间',
    dataIndex: 'genTime',
    scopedSlots: { customRender: 'genTime' }
  },
  {
    title: '确认时间',
    dataIndex: 'confirmTime',
    scopedSlots: { customRender: 'confirmTime' }
  },
  {
    title: '告警信息',
    dataIndex: 'alarmValue'
  },
  {
    title: '点位名称',
    dataIndex: 'positionName'
  },
  {
    title: '告警类型',
    dataIndex: 'alarmType'
  },
  {
    title: '告警级别',
    dataIndex: 'alarmLevel'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    ConfirmAlarm,
    AlarmDetail,
    CreateWorkOrder
  },
  data () {
    this.columns = columns
    return {
      activeKey: '1',
      // create model
      form: this.$form.createForm(this),
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      CreateWorkOrderVisable: false,
      CreateWorkOrdermLoading: false,
      alarmPlace: '',
      visible: false,
      dataId: '',
      confirmLoading: false,
      confirmAlarmLoading: false,
      importVisable: false,
      confirmAlarmVisable: false,
      // 查询参数
      queryParam: {},
      alarmTypeList: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        let strings = this.form.getFieldsValue()
        console.log(strings)
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log(requestParameters, 'requestParametersrequestParameters')
        return findByPage(requestParameters).then(res => {
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {},
  created () {
    this.getAlarmType()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    getAlarmType () {
      getAlarmType().then(res => {
        this.alarmTypeList = res.map(item => {
          return {
            key: item,
            label: item
          }
        })
      })
    },
    handleConfirm (value) {
      this.confirmAlarmVisable = true
      this.dataId = value.id
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleRefsh () {
      this.$refs.table.refresh()
    },
    handleResetData () {
      this.queryParam = {}
      this.$refs.table.refresh()
      this.form.resetFields()
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = {
        ...record,
        genTime: moment(record.genTime).format('YYYY-MM-DD HH:mm:ss'),
        confirmTime: moment(record.confirmTime).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    exportData () {
      this.$message.warning('暂未开发!')
    },
    handleCreateWorkOrderConfirm () {
      const form = this.$refs.CreateWorkOrder.form
      this.CreateWorkOrdermLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          createWorkOrder(values).then(res => {
            submit({
              id: this.dataId
            }).then(res => {
              this.CreateWorkOrderVisable = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('更新成功')
            }).finally(() => {
              this.CreateWorkOrdermLoading = false
            })
          }).finally(() => {
            this.CreateWorkOrdermLoading = false
          })
        }
      })
    },
    handleCreateWorkOrderCancel () {
      this.CreateWorkOrderVisable = false

      const form = this.$refs.CreateWorkOrder.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleConfirmCancel () {
      this.confirmAlarmVisable = false

      const form = this.$refs.confirmAlarm.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleConfirmConfirm () {
      const form = this.$refs.confirmAlarm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          confirm({
            ...values,
            id: this.dataId
          }).then(res => {
            this.confirmAlarmVisable = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.success('更新成功')
          }).finally(() => {
            this.confirmAlarmLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.mdl = null
      this.visible = false

      const form = this.$refs.AlarmDetail.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSubmit (record) {
      this.dataId = record.id
      this.alarmPlace = record.positionName
      this.CreateWorkOrderVisable = true
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handleQueryData (e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}
</style>
